<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from "vue";
import JLoding from "@/components/j-loding/index.vue";
import { Chart } from "../scripts";
import { get } from "@/comm/request";
import { URL_BUY_EQUITY, URL_CAPITAL_EQUITY } from "@/comm/api";
import { LinkeCurrency, LinkeCurrency2 } from "../scripts/CheartConfig";
import JButtons from "@/components/j-buttons/index.vue";
import { useRoute } from "vue-router";
import i18n from "@/locals";
import { useLayout } from "@/stores/layout";
/**时间nav按钮数据 */
/**
 * 缩小三角形
 * 去掉标题栏色块
 * 调低list的item的高度
 * 剧中分类标签
 */
 const layout = useLayout();
const btnsData = [
    {
        label: "H",
        value: "H"
    },
    {
        label: "D",
        value: "D"
    }
];
watch(
    () => layout.newsOpen,
    (newVal, oldVal) => {
        resizeChart();
    }
);
const lodShow = ref(false);
const btns = ref(btnsData);
const idx = ref(btns.value[0]);
const chart_ = ref<any>(null);
const startTime = ref(Date.now() - 7 * 24 * 3600 * 1000);
const route = useRoute();
let token = route.params.id + "";
let chartIns: any = null;
const chartValue = ref<any>(null);
onMounted(async () => {
    // const chart = new Chart(chart_.value);
    // const chart = Chart.addChart(chart_.value as any);
    //在此设置了数据 更改LinkeCurrency里面的图表数据配置然后设置
    // chart.setData(LinkeCurrency);
    // watch(() => useLayout().newsOpen, () => {
    //     setTimeout(() => {
    //         chart.getChart().resize();
    //     }, 200);
    // });
    // if (prop.title === "净买入价值") {
    strReq();
});
onUnmounted(() => {
    window.removeEventListener("resize", resizeChart);
});
interface CharType {
    success: boolean;
    data: Datum[];
}

interface Datum {
    timestamp: number;
    inAmount: number;
    outAmount: number;
    usd: number;
}
const resizeChart = () => {
    if (chartIns) {
        chartIns.chartResize();
    }
};
const strReq = () => {
    //净买入
    if (prop.title == i18n.global.t("message.Token.a")) {
        getChart1Data();
    }
    //净流出
    if (prop.title == i18n.global.t("message.Token.b")) {
        getChart2Data();
    }
};

const getChart1Data = async (type = "H") => {
    lodShow.value = true;
    // console.log("净买入开始时间戳==================================>", prop.klines[0].timestamp, 'Kline', startTime.value)
    let res: CharType = await get(URL_BUY_EQUITY.replace("@", token), { type: type, startTime: startTime.value });
    let chart = new Chart(chart_.value);
    chartValue.value = chart;
   
    //@ts-ignore
    // LinkeCurrency.xAxis.data = res.data.map(item => new Date(item.timestamp).toLocaleDateString());
    LinkeCurrency.xAxis.data = res.data.map(item => item.timestamp);
    //设置买入
    LinkeCurrency.series?.forEach(item => {
        switch (item.name) {
            //买
            case i18n.global.t("message.Token.Cheart.a"):
                item.data = res.data.map(item => item.inAmount);
                break;
            //卖
            case i18n.global.t("message.Token.Cheart.b"):
                item.data = res.data.map(item => item.outAmount);
                break;
            //净买入
            case i18n.global.t("message.Token.Cheart.c"):
                item.data = res.data.map(item => item.inAmount + item.outAmount);
                break;
            //价格(美元)
            case i18n.global.t("message.Token.Cheart.c"):
                item.data = res.data.map(item => item.usd);
                break;
        }
    });
    chart.setData(LinkeCurrency);
    chartIns = chart;
     console.log('净买入图表配置===============>', LinkeCurrency)
    window.addEventListener("resize", resizeChart);
    updatePrice(LinkeCurrency);
    lodShow.value = false;
    if (res.success) {
    }
};

const getChart2Data = async (type = "H") => {
    lodShow.value = true;
    let res: CharType = await get(URL_CAPITAL_EQUITY.replace("@", token), { type: type, startTime: startTime.value });
    // console.log('yzt', prop.title, res)
    lodShow.value = false;
    let chart = new Chart(chart_.value);
    //@ts-ignore
    // LinkeCurrency2.xAxis.data = res.data.map(item => new Date(item.timestamp).toLocaleDateString());
    LinkeCurrency2.xAxis.data = res.data.map(item => item.timestamp);
    //设置买入
    LinkeCurrency2.series?.forEach(item => {
        switch (item.name) {
            //充值
            case i18n.global.t("message.Token.CheartB.a"):
                item.data = res.data.map(item => item.inAmount);
                break;
            //提现
            case i18n.global.t("message.Token.CheartB.b"):
                item.data = res.data.map(item => item.outAmount);
                break;
            //净流出
            case i18n.global.t("message.Token.CheartB.c"):
                item.data = res.data.map(item => item.outAmount + item.inAmount);
                break;
            //价格(美元)
            case i18n.global.t("message.Token.CheartB.d"):
                item.data = res.data.map(item => item.usd);
                break;
        }
    });
    chart.setData(LinkeCurrency2);
    chartIns = chart;
    window.addEventListener("resize", resizeChart);
    updatePrice(LinkeCurrency2);
    if (res.success) {
    }
};

const updatePrice = (obj: any) => {
    // return;
    if (prop.klines?.length && obj.series[3]) {
        let tempAry = obj.xAxis.data.map((i: string) => {
            let t = new Date(i).getTime();
            let item = prop.klines?.find(i => i.timestamp >= t);
            if (item) {
                return item.close;
            }
            // console.log("on find i", i)
            return 0;
        });
        if (chartIns) {
            obj.series[3].data = priceReset(tempAry);
            chartIns.setData(obj);
        } else {
            obj.series.splice(3);
            setTimeout(() => {
                chartIns.setData(obj);
            }, 1000);
        }
    }
    // console.log("jsz " + prop.title, obj)
};

watch(
    () => prop.klines?.length,
    () => {
        if (prop.klines[0].timestamp) {
            startTime.value = prop.klines[0].timestamp;
            // strReq()
        }
        // console.log("jsz", "change kline")
        switch (prop.title) {
            // 净买入价值
            case i18n.global.t("message.Token.a"):
                updatePrice(LinkeCurrency);
                break;
            // CEX净流出
            case i18n.global.t("message.Token.b"):
                updatePrice(LinkeCurrency2);
                break;
        }
    }
);

function priceReset(ary: number[]) {
    let t = 0;
    ary.forEach((i, id, list) => {
        if (i == 0) {
            if (t != 0) {
                list[id] = t;
            }
        } else {
            t = i;
        }
    });
    return ary;
}

const prop = defineProps({
    title: {
        type: String,
        default: "标题"
    },
    klines: {
        type: Array<any>,
        default: []
    }
});

const onTypeChange = function (item: { label: string; value: string }) {
    switch (prop.title) {
        // 净买入价值
        case i18n.global.t("message.Token.a"):
            getChart1Data(item.value);
            break;
        // CEX净流出
        case i18n.global.t("message.Token.b"):
            getChart2Data(item.value);
            break;
    }
};
</script>

<template>
    <div class="cheart">
        <JLoding v-if="lodShow"></JLoding>
        <div class="dedr d-flex justify-space-between">
            <p class="nav-t">{{ prop.title }}</p>
            <JButtons :list="btns" v-model="idx" @change="onTypeChange"></JButtons>
        </div>
        <div ref="chart_" id="chinCoinChart" class="chart-body"></div>
    </div>
</template>

<style lang="scss">
.cheart {
    // padding-inline: 30px;
    // padding-block: 35px;
    height: 100%;
    padding: var(--space);
    background-color: var(--card);
    position: relative;

    .chart-body {
        margin-top: 10px;
        height: calc(100% - var(--space) * 2 - 10px);
    }

    #chinCoinChart {

        // width: 500px;
        // height: 387px;
        div:nth-child(2) {
            color: white !important;
            border: none !important;
            background-color: rgba($color: #000000, $alpha: 0.3) !important;
        }
    }
}

.nav-t {
    // font-weight: 700;
    font-size: 18px;
    font-weight: bold;
    color: var(--color-2);
}
</style>
